package com.dongdongshop.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.api.CartServiceApi;
import com.dongdongshop.api.GoodsServiceApi;
import com.dongdongshop.api.UserServiceApi;
import com.dongdongshop.data.Result;
import com.dongdongshop.dto.AddressDTO;
import com.dongdongshop.dto.CartDTO;
import com.dongdongshop.dto.CartDetailDTO;
import com.dongdongshop.dto.ItemDTO;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.model.TbOrder;
import com.dongdongshop.model.TbOrderExample;
import com.dongdongshop.model.TbOrderItem;
import com.dongdongshop.model.TbOrderItemExample;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.util.IdWorker;
import com.dongdongshop.util.JwtUtil;
import com.dongdongshop.util.LoginUser;
import com.dongdongshop.vo.OrderItemVO;
import com.dongdongshop.vo.OrderVO;
import com.dongdongshop.vo.TradeVO;
import io.jsonwebtoken.Claims;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private TbOrderMapper orderMapper;
    @Resource
    private TbOrderItemMapper orderItemMapper;
    @Autowired
    private CartServiceApi cartServiceApi;
    @Autowired
    private IdWorker idWorker;//雪花算法的不同的id
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UserServiceApi userServiceApi;
    @Autowired
    private GoodsServiceApi goodsServiceApi;

    @Override
    @Transactional//本地事务注解
    @GlobalTransactional(rollbackFor = Exception.class)//添加全局事务注解
    public TradeVO addOrder(String AutharizeToken, Long addressId, String payType) {
        Claims claims = jwtUtil.parseJwt(AutharizeToken);
        LoginUser loginUser = JSONObject.parseObject(claims.getSubject(), LoginUser.class);
        //根据用户id从redis中获取购物车数据
        Result result = cartServiceApi.getCart(AutharizeToken);
        List<CartDTO> cartDTOS = JSONObject.parseArray(JSONObject.toJSONString(result.getData()), CartDTO.class);
        //查询收货人信息
        Result<AddressDTO> addressDTOResult = userServiceApi.getAddressById(addressId);
        AddressDTO addressDTO = addressDTOResult.getData();
        //订单对象的集合
        List<TbOrder> tbOrderList = new ArrayList<>();
        //订单明细的集合
        List<TbOrderItem> orderItemList = new ArrayList<>();
        //扣减库存的集合
        List<ItemDTO> itemDTOlist = new ArrayList<>();
        //定义支付使用订单号
        long out_trade_no = idWorker.nextId();
        //总金额
        BigDecimal allSum = new BigDecimal(0);
        //定义字符串拼接商品标题
        StringBuffer buffer = new StringBuffer();
        for (CartDTO cartDTO : cartDTOS) {
            //一个DTO为一个商家卖的,先保存主表,在保存详细表
            //生成订单id
            long id = idWorker.nextId();
            //创建订单对象
            TbOrder tbOrder = new TbOrder();
            tbOrder.setOrderId(id);//订单id
            tbOrder.setUserId(loginUser.getUserName());//用户ID
            tbOrder.setPaymentType(payType);
            tbOrder.setStatus("1");//未付款
            tbOrder.setCreateTime(new Date());//创建时间
            tbOrder.setUpdateTime(new Date());//修改时间
            tbOrder.setReceiverAreaName(addressDTO.getAddress());//收货人地址
            tbOrder.setReceiver(addressDTO.getContact());//收货人联系人
            tbOrder.setReceiverMobile(addressDTO.getMobile());//收货人手机号
            tbOrder.setSellerId(cartDTO.getSellerId());//商家id
            tbOrder.setOrderNum(String.valueOf(out_trade_no));//支付宝订单号

            //循环明细
            //求总价
            BigDecimal sum = new BigDecimal(0);
            for (CartDetailDTO cartDetailDTO : cartDTO.getDetailList()) {
                sum = sum.add(cartDetailDTO.getTotalFee());
                allSum = allSum.add(cartDetailDTO.getTotalFee());
                buffer.append(cartDetailDTO.getTitle());
                //不能使用double加法计算 ,精度不够
                TbOrderItem orderItem = new TbOrderItem();
                orderItem.setGoodsId(cartDetailDTO.getGoodsId());//SPU_ID
                orderItem.setItemId(cartDetailDTO.getItemId());//商品id
                orderItem.setOrderId(id);//订单id
                orderItem.setId(idWorker.nextId());//id
                orderItem.setPicPath(cartDetailDTO.getPic_path());//图片地址
                orderItem.setPrice(new BigDecimal(cartDetailDTO.getPrice().doubleValue()));//单价
                orderItem.setSellerId(cartDTO.getSellerId());// 商家id
                orderItem.setTitle(cartDetailDTO.getTitle());//商品名称
                orderItem.setTotalFee(new BigDecimal(cartDetailDTO.getTotalFee().doubleValue()));//小计
                orderItem.setNum(cartDetailDTO.getNum());//数量
                orderItem.setOrderNum(String.valueOf(out_trade_no));//支付宝订单号
                orderItem.setStatus("1");//订单状态1 已下单
                orderItemList.add(orderItem);//明细集合
                //扣减库存
                ItemDTO itemDTO = new ItemDTO();
                itemDTO.setId(cartDetailDTO.getItemId());
                itemDTO.setNum(cartDetailDTO.getNum());
                itemDTOlist.add(itemDTO);
            }
            tbOrder.setPayment(sum);//实付金额
            tbOrderList.add(tbOrder);//订单集合
        }
        //批量保存
        //减少库存,调用接口
        goodsServiceApi.subStockCount(itemDTOlist);
        //保存订单
        orderMapper.insertBatch(tbOrderList);
        //int i = 9/0;
        //保存订单明细
        orderItemMapper.insertBatch(orderItemList);
        //调用接口,清除缓存 购物车
        cartServiceApi.deleteCart(AutharizeToken);
        //返回支付用的数据
        TradeVO tradeVO = new TradeVO();
        tradeVO.setOutTradeNo(String.valueOf(out_trade_no));
        tradeVO.setTotalAmount(allSum.toString());
        tradeVO.setSubject(buffer.toString());
        return tradeVO;
    }

    @Override
    @Transactional
    public void updateOrderStatus(String out_trade_no, String trade_no) {
        //先根据订单号查询出来
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andOrderNumEqualTo(out_trade_no);
        List<TbOrder> tbOrderList = orderMapper.selectByExample(example);
        //修改订单流水号
        orderMapper.updateByOrderNo(tbOrderList, trade_no);
        //查询所有的订单详情根据订单号
        TbOrderItemExample itemExample = new TbOrderItemExample();
        TbOrderItemExample.Criteria criteria1 = itemExample.createCriteria();
        criteria1.andOrderNumEqualTo(out_trade_no);
        List<TbOrderItem> orderItemList = orderItemMapper.selectByExample(itemExample);
        //修改订单状态以及流水号
        orderItemMapper.updateByOrderNo(orderItemList, trade_no);

    }

    @Override
    public List<OrderVO> getAllOrderByUser(String AutharizeToken, String flag) {
        Claims claims = jwtUtil.parseJwt(AutharizeToken);
        LoginUser loginUser = JSONObject.parseObject(claims.getSubject(), LoginUser.class);
        //根据loginUser查询当前用户订单信息
        String userName = loginUser.getUserName();
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userName);
        List<TbOrder> tbOrderList = orderMapper.selectByExample(example);
        List<OrderVO> orderVOS = tbOrderList.stream().map(order -> {
            OrderVO vo = new OrderVO();
            BeanUtils.copyProperties(order, vo);
            return vo;
        }).collect(Collectors.toList());
        for (OrderVO orderVO : orderVOS) {
            orderVO.setOrderSid(orderVO.getOrderId().toString());
            TbOrderItemExample example1 = null;
            //判断flag 1为查询全部订单
            if (Objects.equals("1", flag)) {
                example1 = new TbOrderItemExample();
                TbOrderItemExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andOrderIdEqualTo(orderVO.getOrderId());
            } else if (Objects.equals("2", flag)) {
                //2为查询已经付款的
                example1 = new TbOrderItemExample();
                TbOrderItemExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andOrderIdEqualTo(orderVO.getOrderId());
                criteria1.andStatusEqualTo(flag);
            }else if(Objects.equals("3", flag)){
                //退款的
                example1 = new TbOrderItemExample();
                TbOrderItemExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andOrderIdEqualTo(orderVO.getOrderId());
                criteria1.andStatusEqualTo(flag);
            }
            List<TbOrderItem> orderItemList = orderItemMapper.selectByExample(example1);
            List<OrderItemVO> orderItemVOS = orderItemList.stream().map(itemOrder -> {
                OrderItemVO orderItemVO = new OrderItemVO();
                BeanUtils.copyProperties(itemOrder, orderItemVO);
                orderItemVO.setItemOrderId(orderItemVO.getId().toString());
                return orderItemVO;
            }).collect(Collectors.toList());
            orderVO.setOrderItemList(orderItemVOS);
        }
        return orderVOS;
    }

    @Override
    public void refundOrderStatus(Long id) {
        //先根据id查询结果
        TbOrderItem orderItem = orderItemMapper.selectByPrimaryKey(id);
        orderItem.setStatus("3");
        //在修改信息
        orderItemMapper.updateByPrimaryKeySelective(orderItem);
    }

    //定时修改订单
    @Override
    public void updateOrder() {
        //定时去执行签收满七天后,将状态改成8
        //1.查询全部的订单信息,先去判断时间
        List<TbOrder> tbOrderList = orderMapper.selectByExample(null);
        List<Long> ids = new ArrayList<>();
        for (TbOrder order : tbOrderList) {
            long l = System.currentTimeMillis();
            Date updateTime = order.getUpdateTime();
            long time = updateTime.getTime();
            long cha = (l-time)/1000/60/60/24;
            if(cha >= 7){
                ids.add(order.getOrderId());
            }
        }
        //根据id去查询订单详情表
        TbOrderItemExample orderItemExample = new TbOrderItemExample();
        TbOrderItemExample.Criteria criteria = orderItemExample.createCriteria();
        criteria.andOrderIdIn(ids);
        List<TbOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
        if (orderItemList == null){
            return;
        }
        List<TbOrderItem> orderItemList1 = new ArrayList<>();
        for (TbOrderItem orderItem : orderItemList) {
            //判断状态是否为7,如果为7
            if(orderItem.getStatus().equals("7")){
                TbOrderItem tbOrderItem = new TbOrderItem();
                tbOrderItem.setId(orderItem.getId());
                tbOrderItem.setStatus("8");
                // 修改状态为8
                orderItemMapper.updateByPrimaryKeySelective(tbOrderItem);
                orderItemList1.add(tbOrderItem);
            }
        }


    }
}
